﻿using CloudFranceTriple.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace CloudFranceTriple.WebRole.Areas.Portail.Controllers
{
    [CloudFranceTriple.WebRole.Filters.InitializeSimpleMembership]
    public class ShoutBoxApiController : ApiController
    {
        private cloudfrAboq2RsDMEntities db = new cloudfrAboq2RsDMEntities();

        private readonly IWebSecurityWrapper _webSecurity;
        public ShoutBoxApiController()
        {
            this._webSecurity = new WebSecurityWrapper();
        }
        public ShoutBoxApiController(IWebSecurityWrapper webSecurity)
        {
            this._webSecurity = webSecurity;
        }

        // GET api/ShoutBoxApi
        public IEnumerable<ShoutBoxSet> GetShoutBoxSets()
        {

            var userTimeZoneInfo = Extension.GetUserTimeZoneInfo(_webSecurity.CurrentUserId);

            var query = db.ShoutBoxSet.OrderByDescending(shout => shout.CreationDateShoutBox).Take(10).AsEnumerable();
            // Convertir au fuseau horaire de l'utilisateur la date de création du message.
            foreach (ShoutBoxSet message in query)
            {
                message.CreationDateShoutBox = message.CreationDateShoutBox.ToUserTimeZone(userTimeZoneInfo);
            }

            return query;
        }

        // GET api/ShoutBoxApi/5
        public ShoutBoxSet GetShoutBoxSet(int id)
        {
            ShoutBoxSet shoutboxset = db.ShoutBoxSet.Find(id);
            if (shoutboxset == null)
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
            }

            return shoutboxset;
        }

        // PUT api/ShoutBoxApi/5
        [Authorize(Roles = "RoleMember,RoleFans,RoleBaffMember,RoleAdminShoutBox")]
        public HttpResponseMessage PutShoutBoxSet(int id, ShoutBoxSet shoutboxset)
        {
            if (!ModelState.IsValid)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }

            if (id != shoutboxset.Id)
            {
                return Request.CreateResponse(HttpStatusCode.BadRequest);
            }

            db.Entry(shoutboxset).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
            }

            return Request.CreateResponse(HttpStatusCode.OK);
        }

        // POST api/ShoutBoxApi
        [Authorize(Roles = "RoleMember,RoleFans,RoleBaffMember,RoleAdminShoutBox")]
        public HttpResponseMessage PostShoutBoxSet(ShoutBoxSet shoutboxMsg)
        {
            // Pour être créer le message doit exister et ne pas être identique au précédent.
            if ((shoutboxMsg != null && shoutboxMsg.MessageShoutBox != null && shoutboxMsg.MessageShoutBox != String.Empty && ModelState.IsValid)
                && (db.ShoutBoxSet.Where(msg => (msg.MessageShoutBox == shoutboxMsg.MessageShoutBox) && (msg.Id == db.ShoutBoxSet.Max(msg2 => msg2.Id))).Count() == 0))
            {
                shoutboxMsg.CreationDateShoutBox = System.DateTime.UtcNow;
                shoutboxMsg.UserNameAuthorShoutBox = User.Identity.Name;
                db.ShoutBoxSet.Add(shoutboxMsg);
                db.SaveChanges();

                HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, shoutboxMsg);
                response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = shoutboxMsg.Id }));
                return response;
            }
            else
            {
                return Request.CreateResponse();
            }
        }

        // DELETE api/ShoutBoxApi/5
        [Authorize(Roles = "RoleMember,RoleFans,RoleBaffMember,RoleAdminShoutBox")]
        public HttpResponseMessage DeleteShoutBoxSet(int id)
        {
            ShoutBoxSet shoutboxset = db.ShoutBoxSet.Find(id);
            if (shoutboxset == null)
            {
                return Request.CreateResponse(HttpStatusCode.NotFound);
            }

            db.ShoutBoxSet.Remove(shoutboxset);

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
            }

            return Request.CreateResponse(HttpStatusCode.OK, shoutboxset);
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}